#coding=utf-8
import os
import sys
import urllib2
import chardet
from datetime import datetime
from com.jumang.content.BaseCheck import BaseCheck
import time

class WebCheck(BaseCheck):
    type='web app'
    def __init__(self,fullString,event):
        BaseCheck.__init__(self,fullString,event)
        elements=fullString.split('||')
        if len(elements)>4:
          self.url=elements[3].strip()
          # split post form information
          urlData=self.url.split(';')
          if len(urlData)==1:
            self.postData=None
          else:
            self.url=urlData[0]
            self.postData=urlData[1]
          
          #print self.url
          #print self.postData
          
          # filter the display information
          pos=0
          if self.url.find(r'?') ==-1:
            pos=len(self.url)
          else:
            pos=self.url.find(r'?')
          self.server=self.url[:pos]
          self.checkContent=['','']
          self.checkContent[0]=elements[4].strip()
          if len(elements)>5:
          	self.logic=elements[5].strip()
          else:
          	self.logic='include'
          
          self.errorNo=0
          self.errorInfo=''
        else:
          print 'Error: '+fullString

    def check(self):
      self.errorNo=0
      self.errorInfo=''
      try:
        urlConn=urllib2.urlopen(self.url,self.postData,timeout=90)
        content=''
        subContent=''
        subContent=urlConn.read(1024)
        while subContent :
        	content+=subContent
        	subContent=urlConn.read(1024)
        contentEncode= chardet.detect(content)
        #print contentEncode
        #print content
        #content=unicode(content,'UTF-8')
        #print content
        if contentEncode['encoding']=='utf-8':
          pass
        else:
          content=content.decode(contentEncode['encoding']).encode('UTF-8')
        #print content
        if self.logic=='not':
        	if content.find(self.checkContent[0])!=-1:
        		self.errorNo=-555
        		self.errorInfo='Get the special message!'
        else:
        	content.index(self.checkContent[0])
      except urllib2.URLError,error:
        self.errorNo=error.reason
        self.errorInfo=sys.exc_info()[1]
      except IOError,(errorNo,errorInfo):
        self.errorNo=errorNo
        self.errorInfo=errorInfo
      except ValueError,error:
        self.errorNo=-555
        self.errorInfo=error.args
      except:
        self.errorNo=-666
        self.errorInfo=sys.exc_info()[1]
      return (self.errorNo,self.errorInfo)
        